package com.hbsoft.util;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hb.gsonAdapter.DateDefaultAdapter;
import com.hb.gsonAdapter.DoubleDefaultAdapter;
import com.hb.gsonAdapter.IntegerDefaultAdapter;
import com.hb.gsonAdapter.LongDefaultAdapter;

import java.lang.reflect.Type;
import java.util.Date;

public class GsonUtil {

	public static final Gson gson = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerDefaultAdapter())
			.registerTypeAdapter(Double.class, new DoubleDefaultAdapter())
			.registerTypeAdapter(Long.class, new LongDefaultAdapter())
			.registerTypeAdapter(Date.class, new DateDefaultAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss")
			.setExclusionStrategies(new ExclusionStrategy() {
				// 过滤字段
				@Override
				public boolean shouldSkipField(FieldAttributes f) {
					// f.getName().contains("id")|f.getName().contains("address")
					return f.getName().contains("message");
				}

				// 过滤对象
				@Override
				public boolean shouldSkipClass(Class<?> clazz) {
					// clazz.getName().contains("Bean")
					return false;
				}
			}).create();
	
	public static String syncToJson(Object obj){
		return gson.toJson(obj);
	}
	
	public static String toJson(Object obj){
		return gson.toJson(obj);
	}

	public static  <T> T fromJson(String json,Class<T> classOfT){ return gson.fromJson(json,classOfT); }
	
	public static <T> T syncFromJson(String json,Class<T> classOfT){
		return gson.fromJson(json, classOfT);
	}
	
	public static <T> T syncFromJson(String json,Type typeOfT){
		return gson.fromJson(json, typeOfT);
	}

	public static <T> T fromJson(String json,Type typeOfT){
		return gson.fromJson(json, typeOfT);
	}
}
